import time

import requests
import logging

import settings
import util
from common import VideoType

from selenium_worker import HorizontalPublishWorker, VerticalPublishWorker

exit_flag_count = 0

class Executor:
    def __init__(self):
        self.articleList = None

    def get_article(self):
        """
            获取文章
        """
        response = requests.get(settings.GET_ARTICLE_URL)
        try:
            res = response.json()
        except:
            raise RuntimeError("获取文章列表时失败, content: ", response.text)
        if res["code"] == 400:
            raise RuntimeError("获取文章失败")
        else:
            self.articleList = res["result"]

    @staticmethod
    def prepare(article):
        """
        准备工作, 下载视频和封面图
        """
        # 创建文件夹
        folder = util.create_dir(article["id"])

        real_url = util.get_real_download_url(article)
        video_path = util.download_video(real_url, "1", folder)
        article["video_path"] = video_path
        img_path = util.download_pic(article["cover"], "1", folder)
        article["img_path"] = img_path
        util.cut_img(img_path)

    @staticmethod
    def validate(article):
        if article["account"] is None:
            raise  RuntimeError("图文内容分发失败(无对应账号)")

        cookies = article["account"]["cookie"]
        if cookies == "" or cookies is None:
            raise RuntimeError("图文内容分发失败(cookie为空):" + str(article['app_id']))

        token = util.judge_cookie_is_pass(cookies)

        # 检测违禁词汇
        util.contains_prohibited_word(article["content"])

        if article["url"] is None or article["url"] == "":
            raise RuntimeError("视频没有链接")

        if article["content"] is None or article["content"] == "" or len(article["content"]) > 30:
            raise RuntimeError("视频文字不合格")
        util.find_emoji(article["content"])

        # 校验是否能继续发文
        video_type = util.get_video_type(article["video_path"])
        util.judge_account_can_publish(cookies, token, video_type)

    def execute(self):
        self.get_article()
        global exit_flag_count
        for article in self.articleList:
            try:
                self.prepare(article)
                self.validate(article)
                video_type = util.get_video_type(article["video_path"])
                if video_type == VideoType.HORIZONTAL:
                    with HorizontalPublishWorker(article, executor_path=settings.DRIVER_PATH, config=settings.HORIZONTAL) as worker:
                        worker.publish()
                elif video_type == VideoType.VERTICAL:
                    with VerticalPublishWorker(article, executor_path=settings.DRIVER_PATH, config=settings.VERTICAL) as worker:
                        worker.publish()
                else:
                    raise RuntimeError("视频横竖版分析失败!")
                # 发布成功清空 exit_flag_count
                exit_flag_count = 0
            except RuntimeError as runtime_error:
                exit_flag_count = 0
                util.rewrite(4, article["content_id"], str(runtime_error))
            except BaseException as base_exception:
                logging.exception(base_exception)
                util.rewrite(4, article["content_id"], "单流程分发失败")
                # 连续五次单流程失败退出脚本
                exit_flag_count += 1
                if exit_flag_count == settings.exit_count:
                    exit(0)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    while True:
        try:
            Executor().execute()
        except BaseException as e:
            logging.exception(e)
        else:
            pass
        time.sleep(2)

